<?php
/**
 * Topic save action
 */
gatekeeper();
// Get variables
$title = get_input("title");
$desc = get_input("description");
$container_guid = (int) get_input('group_guid');
$rate = get_input("rate");

elgg_make_sticky_form('review');

// validation of inputs
if (!$title || !$desc) {
	register_error(elgg_echo('review:error:missing'));
	forward(REFERER);
}

$container = get_entity($container_guid);
if (!$container || !$container->canWriteToContainer(0, 'object', 'review')) {
	register_error(elgg_echo('review:error:permissions'));
	forward(REFERER);
}

// check whether this is a new review or an edit
$new_review = true;
// if ($guid > 0) {
// 	$new_review = false;
// }

if ($new_review) {
	$review = new ElggObject();
	$review->type = 'object';
	$review->subtype = 'review';
} else {
	// load original file object
	$review = new ElggObject($guid);
	if (!$review || !$review->canEdit()) {
		register_error(elgg_echo('review:review:notfound'));
		forward(REFERER);
	}
}

$review->title = $title;
$review->description = $desc;
$review->rate = $rate;
$review->access_id = ACCESS_PUBLIC;
$review->container_guid = $container_guid;
$review->teacher_guid = elgg_get_logged_in_user_guid();
$result = $review->save();

//$container->rate = $rate;

$project = get_entity ( $container->register_project );
if($project){
	$project->addRelationship($review->guid, 'review');
}

if (!$result) {
	register_error(elgg_echo('review:error:notsaved'));
	forward(REFERER);
}

// review saved so clear sticky form
elgg_clear_sticky_form('review');


// handle results differently for new reviews and review edits
if ($new_review) {
	system_message(elgg_echo('review:review:created'));
	add_to_river('river/object/review/create', 'create', elgg_get_logged_in_user_guid(), $review->guid);
} else {
	system_message(elgg_echo('review:review:updated'));
}

forward($container->getURL());
